package com.safe.first.infrastructure.interceptor;

import com.safe.first.infrastructure.service.RoleService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author Mickey
 * @since 2022/6/13
 **/
@Component
@AllArgsConstructor
public class RolePermissionMetadataSource implements FilterInvocationSecurityMetadataSource {

    private final RoleService roleService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation invocation = (FilterInvocation) object;
        String url = invocation.getRequest().getRequestURI();
        /// 通过请求路径获取访问路径所需的权限列表
        Collection<ConfigAttribute> roles = roleService.getRoleByPath(url);
        if (roles != null && roles.size() > 0) {
            return roles;
        }
        // 没有匹配上的资源，禁止访问，设置不存在的访问权限
        // 如果这里返回空，将会直接放行，运行登录用户访问，这是有风险的
        return SecurityConfig.createList("authenticated");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return roleService.getAllRoles();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
